package pers.apricot.controller

import com.coveo.saml.SamlResponse
import groovy.transform.CompileStatic
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import pers.apricot.service.SamlService

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

@CompileStatic
@Controller
@RequestMapping("saml")
class SmalController {

    @Autowired
    SamlService samlService

    @RequestMapping("loginPage")
    String aaa(Model model) {
        model.addAttribute("action", samlService.samlClient.getIdentityProviderUrl())
        model.addAttribute("requestBody", samlService.buildSmalRequest())
        return "saml/redirect.html"
    }


    @RequestMapping("login")
    String bbb(HttpServletRequest request, HttpServletResponse response, String SAMLResponse, Model model) {
        SamlResponse samlResponse = samlService.samlClient.decodeAndValidateSamlResponse(SAMLResponse, "POST")
        HttpSession session = request.getSession()
        String userCode = samlResponse.getNameID()
        model.addAttribute("name", userCode)
        session.setAttribute("userCode", userCode)
        return "private/loginSuccess.html"
    }
}
